<?php

namespace app\merchants\services;

use app\common\loader\ModelMerchant;
use app\common\loader\Services;
use think\Exception;
use yiqiniu\extend\facade\Arrays;

/**
 * 角色管理
 */
class MerchantRoleService
{
    /**
     * 角色管理分页
     * @param array $options
     * @return array
     * @throws \think\Exception
     */
    public function getPage(array $options): array
    {
        if (empty($options['field'])) {
            $options['field'] = 'id,title,data_permission,description';
        }
        $list = ModelMerchant::MerchantRoles()->page($options);
        Services::Helper()->showListTitle($list['data'], [], ['data_permission' => 'system.data_permission']);
        return $list;
    }

    /**
     * 角色列表
     * @param array $option
     * @param bool $allField
     * @return mixed
     * @throws \think\Exception
     */
    public function getList(array $option, bool $allField = true)
    {
        if (!$allField) {
            $option['field'] = 'id,title';
        }
        return ModelMerchant::MerchantRoles()->setOption($option)->select();

    }


    /**
     * 删除角色
     */
    public function roleDel(int $id, string $mer_id): int
    {
        if (ModelMerchant::Merchant()->where("role_id", $id)->where('mer_id', $mer_id)->count() > 0) {
            api_exception(API_ERROR, "该权限组下存在用户！不能删除");
        }
        $model = ModelMerchant::MerchantRoles();
        if ($model->where("id", $id)->where('mer_id', $mer_id)->where('is_sys', 1)->count() > 0) {
            api_exception(API_ERROR, "系统角色组暂不支持删除");
        }
        return $model->removeOption()->where("id", $id)->where('mer_id', $mer_id)->delete();
    }


    /**
     *  角色组信息
     * @param array $options
     * @return array
     * @throws Exception
     */
    public function roleInfo(array $options): array
    {
        if (empty($options['field'])) {
            $options['field'] = 'id,title,data_permission,description';
        }
        $info = ModelMerchant::MerchantRoles()->find($options);
        $menus = $this->apiActions($info['id'] ?? 0);
        if (empty($info)) {
            $info = ["id" => 0, "title" => "", "data_permission" => 2, "description" => ''];
        }
        $info['menus'] = $menus;
        return $info;
    }

    /**
     *  角色组编辑删除
     * @param array $params
     * @return int|string
     * @throws Exception
     */
    public function roleSave(array $params)
    {
        try {
            return ModelMerchant::MerchantRoles()->addEdit($params);
        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * 权限组详情
     * @param $id
     * @return array
     * @throws \think\Exception
     */
    public function groupInfoSimple($id): array
    {
        try {
            $info = ModelMerchant::MerchantRoles()->where("id", $id)->find();
            if (empty($info)) {
                api_exception(API_TIMEOUT, "权限组不存在");
            }
            return $info;
        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * 根据用户获取当前用户的菜单
     * @param array $adminInfo 当前登录的用户信息
     * @throws \think\Exception
     */
    public function getMerchantMenu(array $adminInfo, $node = true): array
    {
        // 获取对应的菜单
        $method = ModelMerchant::MerchantRolesActions()->where('role_id', $adminInfo['group_id'])->column(null, 'action_method');
        if (!empty($adminInfo['is_sys']) && $adminInfo['is_sys'] == 1) {
            $method = ModelMerchant::MerchantSystemApi()->where(['type_id' => ['=', 0]])->column(null, 'page_action');
        }
        if ($node) {
            $method = ModelMerchant::MerchantSystemMenu()->getMenuAuth($method, true);
        }
        return $method;
    }

    /**
     * 角色管理权限选择
     */
    private function apiActions($roleId)
    {
        $apis = ModelMerchant::MerchantSystemApi()->getActions();
        //是否选择了该权限
        $checkedActions = empty($roleId) ? [] : ModelMerchant::MerchantRolesActions()->where('role_id', $roleId)->column(null, 'action_method');
        foreach ($apis as &$api) {
            if ($api['type_id'] === 0) {
                $api['checked'] = in_array($api['page_action'], $checkedActions);
            }
        }
        $list = Arrays::toTree($apis, 'id', 'pid');
        foreach ($list as $k => $v) {
            if (empty($v['children'])) {
                unset($list[$k]);
            }
        }
        return array_values($list);
    }
}
